import { TOKEN_KEY } from '@/constants'
import type { Profile } from '@/types/user'
import Cookies from 'js-cookie'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import router, { resetRouter } from '@/router'

export const useUserStore = defineStore('user', () => {
  const token = ref(Cookies.get(TOKEN_KEY) || '')

  const setToken = (val: string) => {
    token.value = val
    Cookies.set(TOKEN_KEY, val)
  }

  const removeToken = () => {
    token.value = ''
    Cookies.remove(TOKEN_KEY)
  }

  const logout = () => {
    removeToken()
    setProfile({} as Profile)
    // 清除路由
    resetRouter()
    router.replace('/login')
  }

  // 个人信息
  const profile = ref<Profile>({} as Profile)
  const setProfile = (val: Profile) => {
    profile.value = val
  }

  return { token, setToken, removeToken, logout, profile, setProfile }
})
